package org.phonetic.aspect;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;


public aspect PhoneticLog pertarget(log()){

	private Date dateOne, dateTwo;

	private String getTimeDiff() {
		String diff = "";
		long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
		diff = String.format( 
				"%d hora(s) %d minuto(s) %d segundo(s) %d milisegundo(s)", 
				TimeUnit.MILLISECONDS.toHours( timeDiff ), 
				TimeUnit.MILLISECONDS.toMinutes( timeDiff ) - TimeUnit.HOURS.toMinutes( TimeUnit.MILLISECONDS.toHours( timeDiff ) ), 
				TimeUnit.MILLISECONDS.toSeconds( timeDiff ) - TimeUnit.MINUTES.toSeconds( TimeUnit.MILLISECONDS.toMinutes( timeDiff ) ),
				TimeUnit.MILLISECONDS.toMillis( timeDiff ) - TimeUnit.SECONDS.toMillis( TimeUnit.MILLISECONDS.toSeconds( timeDiff ) )
				);
		return diff;
	}

	pointcut log() : execution( * *.execute(..) );

	pointcut logCreate() : log() && within( PhoneticCreate );

	pointcut logSearch() : log() && within( PhoneticSearch );

	before() : logCreate() {
		dateOne = Calendar.getInstance().getTime();
	}

	before() : logSearch() {
		dateOne = Calendar.getInstance().getTime();
	}

	after() returning() : logCreate(){
		dateTwo = Calendar.getInstance().getTime();
		System.out.println("[FONETIZADOR] Fonetização completa em " + getTimeDiff() );
	}

	after() returning() : logSearch(){
		dateTwo = Calendar.getInstance().getTime();
		System.out.println("[FONETIZADOR] Busca fonética realizada em " + getTimeDiff() );
	}

	after() throwing() : logCreate(){
		System.out.println("[FONETIZADOR-FALHA] Ocorreu um erro na fonetização!");
		dateTwo = Calendar.getInstance().getTime();
	}

	after() throwing() : logSearch(){
		System.out.println("[FONETIZADOR-FALHA] Ocorreu um erro na busca fonética!");
		dateTwo = Calendar.getInstance().getTime();
	}
}
